package com.purchase.ml.service.dealer.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.purchase.ml.bean.base.ApiRestResult;
import com.purchase.ml.bean.req.dealer.*;
import com.purchase.ml.bean.req.mail.DealerStateEditDto;
import com.purchase.ml.bean.req.mail.MailMessage;
import com.purchase.ml.bean.req.sys.SysUserDto;
import com.purchase.ml.bean.res.dealer.SysDealerRes;
import com.purchase.ml.bean.sdk.IpayNewDto;
import com.purchase.ml.bean.vo.dealer.DealerVo;
import com.purchase.ml.consts.CommonConsts;
import com.purchase.ml.consts.Constants;
import com.purchase.ml.consts.MailConstants;
import com.purchase.ml.entity.acc.SysUser;
import com.purchase.ml.entity.dealer.SysAddr;
import com.purchase.ml.entity.dealer.SysDealer;
import com.purchase.ml.entity.dealer.SysResion;
import com.purchase.ml.entity.order.SysPayinfo;
import com.purchase.ml.enums.ConmonStatusEnum;
import com.purchase.ml.enums.OrderStatusEnum;
import com.purchase.ml.enums.RoleTypeEnum;
import com.purchase.ml.enums.SysSeqNameEnum;
import com.purchase.ml.exception.BizException;
import com.purchase.ml.exception.CommonEnum;
import com.purchase.ml.mapper.dealer.SysAddrMapper;
import com.purchase.ml.mapper.dealer.SysDealerMapper;
import com.purchase.ml.mapper.order.SysPayInfoMapper;
import com.purchase.ml.mapper.sys.SysUserMapper;
import com.purchase.ml.security.JwtUtil;
import com.purchase.ml.service.common.CommonSeqService;
import com.purchase.ml.service.dealer.SysDealerService;
import com.purchase.ml.service.email.dealer.CreateDealerEmail;
import com.purchase.ml.service.sdk.Ipay88Service;
import com.purchase.ml.service.sys.SysUserService;
import com.purchase.ml.utils.FileUploadAndDownUtil;
import com.purchase.ml.utils.HttpUtil;
import com.purchase.ml.utils.RedisClient;
import com.purchase.ml.utils.SdkIpay88Utils;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.purchase.ml.exception.CommonEnum.MASTER_DEALER_EXIST_DEALER;

/**
 * @author :zxm
 * @date :2021/2/25 11:15
 * @description :some description
 **/
@Service
@Slf4j
public class SysDealerServiceImpl extends ServiceImpl<SysDealerMapper, SysDealer> implements SysDealerService {
    @Value("${mail.content.sysAddress:https://www.baidu.com/sysAddress}")
    private String sysAddress;  // 系统地址

    @Autowired
    private SysDealerMapper sysDealerMapper;
    @Autowired
    private CommonSeqService commonSeqService;
    @Autowired
    private SysAddrMapper sysAddrMapper;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CreateDealerEmail createDealerEmail;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPayInfoMapper sysPayInfoMapper;

    /**
     * superior: 上级经销商id
     * newType：前端需要传
     * dealer_type:通过newType字段确定
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public ApiRestResult createDealer(SysDealerNewDto dto) {
        // 添加地址
        SysAddr billingAddr = dto.getBillingAddr();
        billingAddr.setAddrId(commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_ADDR_GENERATE.getCode()));
        billingAddr.setType(Constants.BILL_ADDR_INFO);
        SysAddr shopAddr = dto.getShopAddr();
        shopAddr.setAddrId(commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_ADDR_GENERATE.getCode()));
        shopAddr.setType(Constants.SHOP_ADDR_INFO);
        int a = sysAddrMapper.insert(billingAddr);
        int b = sysAddrMapper.insert(shopAddr);
        if (a < 1 || b < 1) {
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        // 添加经 销商
        dto.setCreateAt(new Date());
        dto.setDealerId(commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_DEALER_GENERATE.getCode()));
        dto.setBillingAddrId(billingAddr.getAddrId());
        dto.setShopAddrId(shopAddr.getAddrId());
        dto.setIsAuth(Constants.DEALER_STATE_ENABLE);
        dto.setIsPaid(0);  //支付状态未支付
        //上级ID
        LambdaQueryWrapper<SysDealer> qw = new LambdaQueryWrapper<>();
        qw.eq(SysDealer::getInviteCode,dto.getRegistCode());
        SysDealer supDealer = sysDealerMapper.selectOne(qw);
        if (supDealer==null) {
            throw new BizException(CommonEnum.REGIST_CODE_ERROR);
        }
        dto.setSuperior(supDealer.getDealerId());
        // 创建经销商类型：管理员创建的时候传1 申请传0
        if (dto.getNewType().equals(Constants.NEW_TYPE_DEALER)) {
            dto.setDealerType(CommonConsts.ROLETYPE_DEALER);
            dto.setState(Constants.DEALER_STATE_REQ);
            //需要支付全部设置为上级的Needpay
            dto.setNeedPay(supDealer.getNeedPay());
            // 经销商认证字段
            dto.setIsAuth(Constants.DEALER_STATE_REQ);
        } else if (dto.getNewType().equals(Constants.NEW_TYPE_MASTER_DEALER)) {
            dto.setDealerType(CommonConsts.ROLETYPE_MASTER);
            dto.setState(Constants.DEALER_STATE_ENABLE);
            //查询大代理的邀请码:
            SysDealer sysDealer = sysDealerMapper.selectAgencyDate(CommonConsts.ROLETYPE_AGENCY);
            dto.setRegistCode(sysDealer.getInviteCode()); //注册码为大代理的邀请码
            dto.setNeedPay(0); //主经销商不需要支付
        }
//        // 如果isAgent有值，就创建大代理; todo:暂时不需要
//        if(dto.getIsAgent()!=null && dto.getIsAgent()==Constants.CREATE_OWNER_TYPE){
//            dto.setDealerType(CommonConsts.ROLETYPE_AGENCY);
//            dto.setState(Constants.DEALER_STATE_ENABLE);
//        }
        //非经销商都需要创建邀请码:大代理主经销商
        if (!(CommonConsts.ROLETYPE_DEALER == dto.getDealerType())) {
            // 邀请码
            String inviteCode = "";
            //要求手动输入NUll_INVITCODE
            if (dto.getInviteCode() == null || dto.getInviteCode() == "") {
                throw new BizException(CommonEnum.NUll_INVITCODE);
            }
            inviteCode = dto.getInviteCode();
            LambdaQueryWrapper<SysDealer> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysDealer::getInviteCode, inviteCode);
            Integer count = sysDealerMapper.selectCount(wrapper);
            if (count > 1) {
                //已经存在的不存储
                throw new BizException(CommonEnum.ILLEGAL_INVITCODE);
            }
            dto.setInviteCode(inviteCode);
        }

        if (Constants.ABNORMAL_STATE.equals(dto.getCompanyType())) {
            dto.setEmailAddress(dto.getLoginEmail());
        }
        int isSave = sysDealerMapper.insert(dto);
        if (isSave < 1) {
            throw new BizException(CommonEnum.INSERT_ERROR);
        } else {
            //商户创建成功创建账号
            SysUserDto user = new SysUserDto();
            user.setAcc(dto.getLoginEmail());
            user.setDealerId(dto.getDealerId());
            user.setRoleType(dto.getDealerType());

            user.setHeadUrl(dto.getLogoUrl());
            user.setName(dto.getDealerName());
            user.setEmail(dto.getLoginEmail());
            user.setSalt(CommonConsts.USERKEY);
            user.setIsAdmin(0);
            user.setCreateAt(new Date());
            user.setPwd(dto.getRegisterPwd());
            user.setTelNumber(dto.getRegisterPwd());
            if (CommonConsts.ROLETYPE_DEALER == dto.getDealerType()) {
                user.setState(Constants.ABNORMAL_STATE);
            }
            sysUserService.save(user);
            // 经销商创建的原因
            SysResion sysResion = new SysResion();
            sysResion.setRegisterResion(dto.getReasion());
            sysResion.setDealerId(dto.getDealerId());
            sysDealerMapper.insertDealerResion(sysResion);

            if (CommonConsts.ROLETYPE_MASTER == dto.getDealerType()) {
                // 分别发送邮件到个人邮箱和公司邮箱
                MailMessage msgObj2Acc = createDealerEmail.getMasterCreateMessage(user.getAcc(), user.getName());
                String msg2Acc = JSON.toJSONString(msgObj2Acc);
                RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, msg2Acc);
                if (!user.getAcc().equals(dto.getEmailAddress())) {
                    MailMessage msgObj2Mdealer = createDealerEmail.getMasterCreateMessage(dto.getEmailAddress(), dto.getDealerName());
                    String msg2Mdealer = JSON.toJSONString(msgObj2Mdealer);
                    RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, msg2Mdealer);
                }
            } else if (CommonConsts.ROLETYPE_DEALER == dto.getDealerType()) {
                MailMessage msgObj = createDealerEmail.getDealerAuthMessage(dto.getLoginEmail());
                String message = JSON.toJSONString(msgObj);
                RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, message);
            }
        }
        return ApiRestResult.ok();
    }
    @Transactional
    @Override
    public ApiRestResult editDealer(SysDealerEditDto dto) {
        //获取账号信息
        SysUser sysUser = JwtUtil.getCurrentUser();
        // 获取经销商；如果是经销商只能修改自己
        SysDealer sysDealer = sysDealerMapper.selectById(dto.getId());
        if (sysUser.getRoleType().equals(CommonConsts.ROLETYPE_MASTER)) {
            //住经销商只允许修改自己下游
            if (sysDealer.getDealerType().equals(CommonConsts.ROLETYPE_DEALER) && !sysDealer.getSuperior().equals(sysUser.getDealerId())) {
                throw new BizException(CommonEnum.UPDATE_ERROR);
            }
        }
        //如果是经销商只允许自己
        if (sysUser.getRoleType().equals(CommonConsts.ROLETYPE_DEALER)) {
            //住经销商只允许修改自己下游
            if (!sysDealer.getDealerId().equals(sysUser.getDealerId())) {
                throw new BizException(CommonEnum.UPDATE_ERROR);
            }
        }

        if (sysDealer == null) {
            throw new BizException(CommonEnum.NO_EXIST_DEALER);
        }

        // 不允许修改的字段
        dto.setRegistCode(sysDealer.getRegistCode());
        dto.setSuperior(sysDealer.getSuperior());
        dto.setInviteCode(sysDealer.getInviteCode());
        dto.setDealerId(sysDealer.getDealerId());
        dto.setDealerType(sysDealer.getDealerType());

        //不是大代理不允许修改 付款方式
        if (!sysUser.getRoleType().equals(CommonConsts.ROLETYPE_AGENCY)) {
            dto.setNeedPay(sysDealer.getNeedPay());
        }

        int a = 0;
        int b = 0;
        if (dto.getShopAddr().getId() == null || dto.getBillingAddr().getId() == null) {
            SysAddr shopAddr = dto.getShopAddr();
            shopAddr.setAddrId(sysDealer.getShopAddrId());
            a = sysAddrMapper.insert(shopAddr);
            SysAddr billingAddr = dto.getShopAddr();
            billingAddr.setAddrId(sysDealer.getBillingAddrId());
            b = sysAddrMapper.insert(billingAddr);
        } else {
            a = sysAddrMapper.updateById(dto.getBillingAddr());
            b = sysAddrMapper.updateById(dto.getShopAddr());
        }
        if (a < 1 || b < 1) {
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }
        // 处理logoUrl图片
        File fileDir = FileUploadAndDownUtil.getImgDirFile();
        if (sysDealer.getCertificateUrl() == null) {
            throw new BizException(CommonEnum.UPDATE_ERROR_NOURL);
        }
        File certificateFile = new File(fileDir.getAbsolutePath(), sysDealer.getCertificateUrl());
        if (certificateFile.exists() && !dto.getCertificateUrl().equals(sysDealer.getCertificateUrl())) {
            FileUploadAndDownUtil.deleteFile(certificateFile);
        }
        if (Constants.ABNORMAL_STATE.equals(sysDealer.getCompanyType())) {
            File utilFile = new File(fileDir.getAbsolutePath(), sysDealer.getUtilityBillUrl());
            if (utilFile.exists() && !dto.getUtilityBillUrl().equals(sysDealer.getUtilityBillUrl())) {
                FileUploadAndDownUtil.deleteFile(utilFile);
            }
        }
        if (Constants.NORMAL_STATE.equals(sysDealer.getCompanyType())) {
            File logoFile = new File(fileDir.getAbsolutePath(), sysDealer.getLogoUrl());
            if (logoFile.exists() && !dto.getLogoUrl().equals(sysDealer.getLogoUrl())) {
                FileUploadAndDownUtil.deleteFile(logoFile);
            }
        }
        dto.setUpdateAt(new Date());
        //如果修改为禁用则禁用账号；
        if (dto.getState() == Constants.DEALER_STATE_DISABLE) {
            userMapper.updateAccState(dto.getDealerId(), Constants.ABNORMAL_STATE);
        }
        int isUpdate = sysDealerMapper.updateById(dto);
        if (isUpdate < 1) {
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }else{
            //如果大代理更新了 needpay字段
            if(sysUser.getRoleType().equals(CommonConsts.ROLETYPE_AGENCY)){
                if(dto.getNeedPay() != null){
                    sysDealerMapper.updateSonDealerNeedPay(dto.getDealerId(),dto.getNeedPay());
                }
            }
        }
        return ApiRestResult.ok();
    }

    @Override
    public IPage<SysDealer> masterDealerQuery(SysDealerQueryDto dto) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        IPage<SysDealer> page = new Page<SysDealer>(dto.getPageIndex(), dto.getPageNum());
        QueryWrapper<SysDealer> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.hasText(dto.getDealerName()), "dealer_name", dto.getDealerName());
        if (Integer.valueOf(CommonConsts.ROLETYPE_AGENCY).equals(currentUser.getRoleType())
                && Constants.DEALER_STATE_REQ.equals(dto.getState())) {
            wrapper.ne("dealer_type", CommonConsts.ROLETYPE_AGENCY);
        } else {
            wrapper.eq("dealer_type", CommonConsts.ROLETYPE_MASTER);
        }
        if (dto.getSort() != null && dto.getOrder() != null) {
            if (dto.getSort() == Constants.ASC_ORDER) {
                wrapper.orderByAsc(dto.getOrder());
            } else if (dto.getSort() == Constants.DESC_ORDER) {
                wrapper.orderByDesc(dto.getOrder());
            }
        } else {
            wrapper.orderByAsc("id");
        }
        // 不查询删除的
        wrapper.ne("`state`", Constants.DEALER_STATE_DELETE);
        wrapper.eq(dto.getState() != null, "state", dto.getState());
        wrapper.eq("is_auth", Constants.DEALER_STATE_ENABLE);
        IPage<SysDealer> dealerIPage = sysDealerMapper.selectPage(page, wrapper);
        List<SysDealer> dealerList = dealerIPage.getRecords();
        for (SysDealer sysDealer : dealerList) {
            SysAddr shopAddr = sysAddrMapper.findAddrByAddrId(sysDealer.getShopAddrId());
            sysDealer.setShopAddr(shopAddr);
            SysAddr billingAddr = sysAddrMapper.findAddrByAddrId(sysDealer.getBillingAddrId());
            sysDealer.setBillingAddr(billingAddr);
            SysResion sysResion = sysDealerMapper.selectRegisterResion(sysDealer.getDealerId());
            if (sysResion != null) {
                sysDealer.setRegisterResion(sysResion.getRegisterResion());
            }
        }
        return dealerIPage;
    }

    @Override
    public List<SysDealerRes> queryMasterDealer() {
        // 查询所有主经销商
        LambdaQueryWrapper<SysDealer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDealer::getDealerType, CommonConsts.ROLETYPE_MASTER);
        wrapper.ne(SysDealer::getState, Constants.DEALER_STATE_DELETE);
        List<SysDealer> dbDealerList = sysDealerMapper.selectList(wrapper);
        // 将查询到的对象转换为返回给前端的对象
        List<SysDealerRes> sysDealerRes = mapperFacade.mapAsList(dbDealerList, SysDealerRes.class);
        return sysDealerRes;
    }

    @Deprecated
    @Override
    public IPage<SysDealer> queryPendingDealer(SysDealerQueryDto dto) {
        IPage<SysDealer> page = new Page<>(dto.getPageIndex(), dto.getPageNum());
        QueryWrapper<SysDealer> wrapper = new QueryWrapper<>();
        //只要经销商
        wrapper.eq("dealer_type", CommonConsts.ROLETYPE_DEALER);
        wrapper.eq("state", ConmonStatusEnum.PADING.getCode());
        wrapper.orderByAsc("id");
        IPage<SysDealer> dealerIPage = sysDealerMapper.selectPage(page, wrapper);
        return dealerIPage;
    }

    @Override
    public void notifyMail(String token) {
        Long userId = JwtUtil.getUserId(token);
        SysUser user = userMapper.selectById(userId);
        // 查询当前用户所对应的经销商
        LambdaQueryWrapper<SysDealer> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysDealer::getDealerId, user.getDealerId());
        SysDealer sysDealer = sysDealerMapper.selectOne(wrapper1);
        // 查询当前经销商的主经销商及对应用户
        LambdaQueryWrapper<SysDealer> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SysDealer::getDealerId, sysDealer.getSuperior());
        SysDealer mDealer = sysDealerMapper.selectOne(wrapper2);
        SysUser mUser = sysUserMapper.selectByDealerId(mDealer.getDealerId());

        // 分别发送邮件到个人邮箱和公司邮箱
        MailMessage msgObjA = createDealerEmail.getDealerNotifyMessage(user.getAcc(), user.getName());
        String messageA = JSON.toJSONString(msgObjA);
        RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, messageA);
        if (!user.getAcc().equals(sysDealer.getEmailAddress())) {
            MailMessage mailObj2Dealer = createDealerEmail.getDealerNotifyMessage(sysDealer.getEmailAddress(), sysDealer.getDealerName());
            String msg2Dealer = JSON.toJSONString(mailObj2Dealer);
            RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, msg2Dealer);
        }
        MailMessage msgObjB = createDealerEmail.getMdealerNotifyMessage(mUser.getAcc(), mUser.getName(), user.getName());
        String messageB = JSON.toJSONString(msgObjB);
        RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, messageB);
        if (!mUser.getAcc().equals(mDealer.getEmailAddress())) {
            MailMessage mailObj2Mdealer = createDealerEmail.getMdealerNotifyMessage(mDealer.getEmailAddress(), mDealer.getDealerName(), sysDealer.getDealerName());
            String msg2Mdealer = JSON.toJSONString(mailObj2Mdealer);
            RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, msg2Mdealer);
        }
        // 重定向到系统页面
        try {
            HttpUtil.getResponse().sendRedirect(sysAddress);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void verifyDealer(DealerStateEditDto dto) {
        // 查询当前申请的经销商
        SysDealer sysDealer = sysDealerMapper.selectById(dto.getId());
        // 查询当前经销商的主经销商
        LambdaQueryWrapper<SysDealer> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysDealer::getDealerId, sysDealer.getSuperior());
        SysDealer mDealer = sysDealerMapper.selectOne(wrapper1);
        // 主经销商的上级==>大代理
        LambdaQueryWrapper<SysDealer> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SysDealer::getDealerId, mDealer.getSuperior());
        SysDealer agentDealer = sysDealerMapper.selectOne(wrapper2);
        // 查询大代理的用户信息
        SysUser sysUser = sysUserMapper.selectByDealerId(agentDealer.getDealerId());
        MailMessage msgObj = createDealerEmail.getMdealerHandleMessage(sysUser.getAcc(), sysUser.getName(), mDealer.getDealerName(), sysDealer.getDealerName());
        String message = JSON.toJSONString(msgObj);
        RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE, message);

        sysDealer.setIsAuth(Constants.DEALER_STATE_ENABLE);
        sysDealerMapper.updateById(sysDealer);
    }

    @Override
    public List<DealerVo> getCurrentUserDear() {
        SysUser currentUser = JwtUtil.getCurrentUser();
        Integer roleType = currentUser.getRoleType();
        List<DealerVo> list = new ArrayList<>();
        QueryWrapper<SysDealer> wrapper = new QueryWrapper<>();
        switch (roleType) {
            case CommonConsts.ROLETYPE_ADMIN:
                //管理员
                wrapper.ne("state", Constants.DEALER_STATE_DELETE); //需要统计非删除的
                list = sysDealerMapper.selectList(wrapper).stream().map(e -> new DealerVo(e.getDealerId(), e.getDealerType(), e.getState(),e.getIsAuth())).collect(Collectors.toList());
                break;
            case CommonConsts.ROLETYPE_AGENCY:
                //大代理
                wrapper.eq("superior", currentUser.getDealerId());
                wrapper.ne("state", Constants.DEALER_STATE_DELETE);
                list = sysDealerMapper.selectList(wrapper).stream().map(e -> new DealerVo(e.getDealerId(), e.getDealerType(), e.getState(),e.getIsAuth())).collect(Collectors.toList());
                List<DealerVo> voList = null;
                if (list != null && list.size() > 0) {
                    QueryWrapper<SysDealer> wrapper2 = new QueryWrapper<>();
                    wrapper2.in("superior", list.stream().map(e -> e.getDealerId()).collect(Collectors.toList()).toArray());
                    voList = sysDealerMapper.selectList(wrapper2).stream().map(e -> new DealerVo(e.getDealerId(), e.getDealerType(), e.getState(),e.getIsAuth())).collect(Collectors.toList());
                }
                if(voList!=null &&voList.size()>0){
                    list.addAll(voList);
                }
                //              无需统计自己
//                list.add(new DealerVo(currentUser.getDealerId(),currentUser.getRoleType(),currentUser.getState()));
                break;
            case CommonConsts.ROLETYPE_MASTER:
                //主经销商
                wrapper.eq("superior",currentUser.getDealerId());
                wrapper.ne("state",Constants.DEALER_STATE_DELETE);
                list = sysDealerMapper.selectList(wrapper).stream().map(e -> new DealerVo(e.getDealerId(), e.getDealerType(),e.getState(),e.getIsAuth())).collect(Collectors.toList());
                log.info("list===22222========={}",list);
//              无需统计自己
//              list.add(new DealerVo(currentUser.getDealerId(),currentUser.getRoleType(),currentUser.getState()));
                log.info("list===22222========={}",list);
                break;
            case CommonConsts.ROLETYPE_DEALER:
                //经销商
                list.add(new DealerVo(currentUser.getDealerId(),currentUser.getRoleType(),currentUser.getState(),1));
                break;
        }
        return list;
    }

    @Override
    public SysDealer queryDealerByDealerId(SysDealerDto dto) {
        SysDealer sysDealer = sysDealerMapper.selectByDealerId(dto.getDealerId());
        if (sysDealer == null) {
            throw new BizException(CommonEnum.NO_EXIST_DEALER);
        }
        // 查询出该经销商的地址
        SysAddr shopAddr = sysAddrMapper.findAddrByAddrId(sysDealer.getShopAddrId());
        SysAddr billingAddr = sysAddrMapper.findAddrByAddrId(sysDealer.getBillingAddrId());
        sysDealer.setShopAddr(shopAddr);
        sysDealer.setBillingAddr(billingAddr);
        return sysDealer;
    }

    @Override
    public SysDealer findCurrentDealer() {
        Long userId = JwtUtil.getUserId();
        SysUser sysUser = userMapper.selectById(userId);
        SysDealer sysDealer = sysDealerMapper.selectByDealerId(sysUser.getDealerId());

        // 查询该经销商的账单地址和收货地址
        SysAddr billingAddr = sysAddrMapper.findAddrByAddrId(sysDealer.getBillingAddrId());
        sysDealer.setBillingAddr(billingAddr);
        SysAddr shopAddr = sysAddrMapper.findAddrByAddrId(sysDealer.getShopAddrId());
        sysDealer.setShopAddr(shopAddr);
        SysResion sysResion = sysDealerMapper.selectRegisterResion(sysDealer.getDealerId());
        if(sysResion != null){
            sysDealer.setRegisterResion(sysResion.getRegisterResion());
        }
        return sysDealer;
    }

    @Override
    public IPage<SysDealer> findAllPendingDealer(SysDealerQueryDto dto) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        SysDealer sysDealer = sysDealerMapper.selectByDealerId(currentUser.getDealerId());

        IPage<SysDealer> page = new Page<SysDealer>(dto.getPageIndex(), dto.getPageNum());
        QueryWrapper<SysDealer> wrapper = new QueryWrapper<>();

        // 管理员，大代理查询所有已认证，待定的经销商！！主经销商查询自己待定的经销商
        if (!Integer.valueOf(CommonConsts.ROLETYPE_MASTER).equals(currentUser.getRoleType())) {
            wrapper.eq("is_auth", Constants.DEALER_STATE_ENABLE);
            wrapper.eq("state", Constants.NORMAL_STATE);  // 申请
            wrapper.eq("dealer_type",CommonConsts.ROLETYPE_DEALER);
        } else {
            wrapper.eq("is_auth", Constants.DEALER_STATE_REQ);
            wrapper.eq("state", Constants.NORMAL_STATE);
            wrapper.eq("superior", sysDealer.getDealerId());
        }
        if (dto.getSort() != null && dto.getOrder() != null) {
            if (dto.getSort().equals(Constants.ASC_ORDER)) {
                wrapper.orderByAsc(dto.getOrder());
            } else if (dto.getSort().equals(Constants.DESC_ORDER)) {
                wrapper.orderByDesc(dto.getOrder());
            }
        } else {
            wrapper.orderByAsc("id");
        }
        IPage<SysDealer> dealerIPage = sysDealerMapper.selectPage(page, wrapper);
        List<SysDealer> dealerList = dealerIPage.getRecords();
        for (SysDealer dealer : dealerList) {
            SysAddr shopAddr = sysAddrMapper.findAddrByAddrId(dealer.getShopAddrId());
            dealer.setShopAddr(shopAddr);
            SysAddr billingAddr = sysAddrMapper.findAddrByAddrId(dealer.getBillingAddrId());
            dealer.setBillingAddr(billingAddr);
            SysResion sysResion = sysDealerMapper.selectRegisterResion(dealer.getDealerId());
            if (sysResion != null) {
                dealer.setRegisterResion(sysResion.getRegisterResion());
            }
        }
        return dealerIPage;
    }

    @Override
    public void batchDeleteDealer(List<Long> ids) {
        for (Long id : ids) {
            SysDealer sysDealer = sysDealerMapper.selectById(id);
            if( !(CommonConsts.ROLETYPE_DEALER == sysDealer.getDealerType()) ){
                LambdaQueryWrapper<SysDealer> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysDealer::getSuperior,sysDealer.getDealerId());
                wrapper.ne(SysDealer::getState,Constants.DEALER_STATE_DELETE);
                Integer count = sysDealerMapper.selectCount(wrapper);
                if(count > 0){
                    throw new BizException(
                            MASTER_DEALER_EXIST_DEALER.getResultCode(),sysDealer.getDealerName()+MASTER_DEALER_EXIST_DEALER.getResultMsg());
                }
            }
            int i = sysDealerMapper.updateDealerState(id,Constants.DEALER_STATE_DELETE);
            //查询经销商；禁用账号22223333
            userMapper.updateAccState(sysDealer.getDealerId(),Constants.ABNORMAL_STATE);
            if(i < 1){
                throw new BizException(CommonEnum.DELETE_ERROR);
            }
        }
    }

    @Override
    public IPage<SysDealer> queryAllDealerById(SysDealerQueryDto dto) {
        SysUser user = JwtUtil.getCurrentUser();
        if(dto.getId() == null){
            SysDealer sysDealer = sysDealerMapper.selectByDealerId(user.getDealerId());
            dto.setId(sysDealer.getId());
        }
        // 得到该主经销商的经销商id
        Page<SysDealer> page = new Page<>(dto.getPageIndex(), dto.getPageNum());
        QueryWrapper<SysDealer> wrapper = new QueryWrapper<>();
        SysDealer sysDealer = sysDealerMapper.selectById(dto.getId());
        wrapper.like(StringUtils.hasText(dto.getDealerName()),"dealer_name",dto.getDealerName());
        wrapper.eq(dto.getState()!=null,"state",dto.getState());
        if(dto.getSort()!=null && dto.getOrder()!=null){
            if(dto.getSort().equals(Constants.ASC_ORDER)){
                wrapper.orderByAsc(dto.getOrder());
            }else if(dto.getSort().equals(Constants.DESC_ORDER)){
                wrapper.orderByDesc(dto.getOrder());
            }
        }else {
            wrapper.orderByAsc("id");
        }
        // 不查询删除的
        wrapper.ne("`state`", Constants.DEALER_STATE_DELETE);
        wrapper.eq("superior", sysDealer.getDealerId());
        if(!Integer.valueOf(CommonConsts.ROLETYPE_MASTER).equals(user.getRoleType())){
            wrapper.eq("is_auth",Constants.DEALER_STATE_ENABLE);
        }
        Page<SysDealer> dealerIPage = sysDealerMapper.selectPage(page, wrapper);
        List<SysDealer> dealerList = dealerIPage.getRecords();
        for (SysDealer dealer:dealerList) {
            SysAddr shopAddr = sysAddrMapper.findAddrByAddrId(dealer.getShopAddrId());
            dealer.setShopAddr(shopAddr);
            SysAddr billingAddr = sysAddrMapper.findAddrByAddrId(dealer.getBillingAddrId());
            dealer.setBillingAddr(billingAddr);
            SysResion sysResion = sysDealerMapper.selectRegisterResion(dealer.getDealerId());
            if(sysResion != null){
                dealer.setRegisterResion(sysResion.getRegisterResion());
            }
        }
        return dealerIPage;
    }
    /**
   * 支付成功变更状态:修改邀请码
   * */
    @Override
    public int updateDealerStateEnable(Long dealerId) {
        //查询上级邀请码
        //查询上级当前已有的数量商户数量
        //组织变更参数：邀请码；状态
        int updateNum = sysDealerMapper.updateDealerStateByDealerId(dealerId,Constants.DEALER_STATE_ENABLE);
        return updateNum;
    }

    @Override
    public SysDealer findByDealerId(Long dealerId) {
        return sysDealerMapper.selectByDealerId(dealerId);
    }

    @Transactional
    @Override
    public boolean updateStateById(DealerStateEditDto dto) {
        dto.setUpdateAt(new Date());
        int isUpdate = sysDealerMapper.updateById(dto);
        if(isUpdate < 1){
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }
        SysDealer dealer = sysDealerMapper.selectById(dto);
        // 修改用户状态
        int i = sysUserMapper.updateAccState(dealer.getDealerId(), Constants.NORMAL_STATE);
        if(i < 1){
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }
        // 查询到当前经销商对应的用户
        SysUser sysUser = sysUserMapper.selectByDealerId(dealer.getDealerId());
        MailMessage msgObj = createDealerEmail.getPassNotifyMessage(sysUser.getAcc(), sysUser.getName());
        String message = JSON.toJSONString(msgObj);
        RedisClient.lpush(MailConstants.REDIS_MAIL_MESSAGE,message);
        return true;
    }

    @Override
    public Map<String,String> registerPay(SysDealerRegisterPayDto dto) throws NoSuchAlgorithmException {
        //查询当前的账号
        SysUser sysUser = JwtUtil.getCurrentUser();
//        查询当前的经销商；
//        SysDealer sysDealer = sysDealerMapper.selectByDealerId(sysUser.getDealerId());
        IpayNewDto ipayNewDto = new IpayNewDto();
        ipayNewDto.setPayType(Constants.PAY_ORDER_TYPE_REGIST);
        ipayNewDto.setRefNo(dto.getDealerId().toString());
        ipayNewDto.setAmount( new BigDecimal(Constants.PAY_REGISTER_MONEY) );
        ipayNewDto.setProdDesc("RegistFee");
        ipayNewDto.setUserName(sysUser.getName());
        ipayNewDto.setUserEmail(sysUser.getEmail());
        ipayNewDto.setUserContact(sysUser.getTelNumber());
        //
        //创建支付订单
        SysPayinfo sysPayinfo = new SysPayinfo();
        sysPayinfo.setCreateAt(new Date());
        sysPayinfo.setMoney( new BigDecimal(Constants.PAY_REGISTER_MONEY) );
        sysPayinfo.setPayId( dto.getDealerId() );
        sysPayinfo.setPayMethod("RegistFee");
        sysPayinfo.setState(OrderStatusEnum.UNPAID.getCode());
        sysPayinfo.setType(Constants.PAY_ORDER_TYPE_REGIST);
        //避免同一个经销商多次提交而不支付；创建之前线检查之前的订单；如果有未支付的直接删除
        QueryWrapper<SysPayinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("pay_id",dto.getDealerId());
        wrapper.eq("state", ConmonStatusEnum.PADING.getCode());
        SysPayinfo sysPayinfoObj = sysPayInfoMapper.selectOne(wrapper);
        if(sysPayinfoObj != null){
            sysPayInfoMapper.deleteById(sysPayinfoObj.getId());
        }

        int insertNum = sysPayInfoMapper.insert(sysPayinfo);
        if(insertNum > 0){
            return SdkIpay88Utils.doRequestToIpay88(ipayNewDto);
        }
        return null;
    }
}
